package com.zrj.utils;

import com.zrj.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhaorujie
 * @version 1.0
 * @date 2021/6/24 14:22
 */
public class HtmlParseUtil {
    public static void main(String[] args) throws Exception {
        //parseJd("科幻").forEach(System.out::println);
        wallpaper("壁纸").forEach(System.out::println);
    }
    public static List<Content> parseJd(String keyword) throws Exception {
        //获取请求 https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        //解析网页（Jsoup返回Document就是浏览器Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有你在js中可以使用的方法，在这里都能用
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        List<Content> list = new ArrayList<>();
        for (Element el : elements) {
            //关于这种图片特别多的网站，所有的图片都是延迟加载的
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            list.add(content);
        }
        return list;
    }

    public static List<Object> wallpaper(String keyword) throws IOException {
        String url = "https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=" + keyword + "&fr=ala&ala=1&alatpl=wallpaper&pos=0";
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("imgid");
        Elements elements = element.getElementsByTag("li");
        List<Object> list = new ArrayList<>();
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            list.add(img);
        }
        return list;
    }
}
